package com.winning.pmph.utils;

import org.apache.commons.collections.CollectionUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;


public class KmsHttpServletRequestWrapper extends HttpServletRequestWrapper {

    private Map<String, String[]> params = new HashMap<>();

    public KmsHttpServletRequestWrapper(HttpServletRequest request) {
        super(request);
        //将现有parameter传递给params
        addParameterMap(request.getParameterMap());
    }

    /**
     * 重载构造函数
     * @param request
     * @param extraParams
     */
    public KmsHttpServletRequestWrapper(HttpServletRequest request, Map<String, String[]> extraParams) {
        this(request);
        addParameterMap(extraParams);
    }

    /* 重写父类方法
     * 自定义参数
     */
    public Enumeration<String> getParameterNames() {
        Set set=params.keySet();
        if (CollectionUtils.isNotEmpty(set)){
            return Collections.enumeration(set);
        }else {
            return super.getParameterNames();
        }
    }

    /**
     * 重写getParameter，代表参数从当前类中的map获取
     * @param name
     * @return
     */
    @Override
    public String getParameter(String name) {
        String[] values = params.get(name);
        if(values == null || values.length == 0) {
            return null;
        }
        return values[0];
    }

    /**
     * 同上
     * @param name
     * @return
     */
    @Override
    public String[] getParameterValues(String name) {
        return params.get(name);
    }

    private void addParameterMap(Map<String, String[]> parameterMap) {
        parameterMap.forEach(this::addParameter);
    }

    /**
     * 添加参数
     * @param name
     * @param value
     */
    public void addParameter(String name, String[] value) {
        value = Stream.of(value)
                .filter(item -> !Objects.equals(item, "null") && !Objects.equals(item, "undefined"))
                .collect(Collectors.toList()).toArray(new String[0]);
        params.put(name, value);
    }
}